import cv2

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

import config
from ui_test import *
from camera import Camera
from config import selectImage_flag


GraphicsViewLong = 640
GraphicsViewWidth = 480


# 显示图片

class GraphicsView(QGraphicsView):
    def __init__(self, parent=None,camera= None):
        super(GraphicsView, self).__init__(parent=parent)
        self._zoom = 0
        self._empty = True
        self._photo = QGraphicsPixmapItem()
        self._scene = QGraphicsScene(self)
        self._scene.addItem(self._photo)
        self.setScene(self._scene)

        self.setAlignment(Qt.AlignCenter)  # 居中显示
        self.setDragMode(QGraphicsView.ScrollHandDrag)  # 设置拖动
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # todo  一律不许出现魔法值

        self.setMinimumSize(GraphicsViewLong, GraphicsViewWidth)

        # # self.label = QtWidgets.QLabel(self.centralwidget)
        # self.label = QLabel()
        #
        # # self.label.setGeometry(QtCore.QRect(20, 40, 851, 721))
        # self.label.setGeometry(QtCore.QRect(20, 40, 851, 721))
        #
        # self.label.setObjectName("label")

        # self.label.hide()

        # self.setVisible(True)

        # # ui
        #
        # self.ui = Ui_MainWindow()
        # self.ui.setupUi(self)


        # ## 照相机 常显
        #
        self.cam1 = camera
        #  计数器
        self.timer_camera = QTimer()
        # self.timer_camera.timeout.connect(self.show_image_on_label)
        # self.timer_camera.start(100)

        # self.flag = True

        # self.display()


    def displayCamera(self):

        self.timer_camera.timeout.connect(self.show_image_on_label)
        self.timer_camera.start(100)


    #  关闭 摄像机
    def takeoffCamera(self):

        self.timer_camera.stop()




    def display(self):

        # self._scene.removeItem(self._photo)
        #
        # # self.label.setGeometry(QtCore.QRect(20, 40, 851, 721))
        #
        # self._scene.addItem(self.label)

        config.selectImage_flag = True



    def show_image_on_label(self):


        self.image = self.cam1.show_thread()

        # print(type(self.image))
        # print(type(self.image.data))
        # print(self.image.shape)
        # print(self.image.data.shape)

        # show = self.crop_image(self.image, 400, 400)

        show = cv2.resize(self.image, (int(640), int(480)))  # 把读到的帧的大小重新设置为 640x480

        show = show[130:380, :, :]

        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)

        # print(show.shape)

        # showImage = QImage(show.data, show.shape[1]-100, show.shape[0]-100, QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式

        showImage = QImage(show.data, show.shape[1], show.shape[0],
                           QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式

        # self.ui.label.setPixmap(QPixmap.fromImage(showImage))  # 往显示视频的Label里 显示QImage
        self._photo.setPixmap(QPixmap.fromImage(showImage))

    def contextMenuEvent(self, event):
        if not self.has_photo():
            return
        menu = QMenu()
        save_action = QAction('另存为', self)
        save_action.triggered.connect(self.save_current)  # 传递额外值
        menu.addAction(save_action)
        menu.exec(QCursor.pos())

    def save_current(self):
        file_name = QFileDialog.getSaveFileName(self, '另存为', './', 'Image files(*.jpg *.gif *.png)')[0]
        print(file_name)
        if file_name:
            self._photo.pixmap().save(file_name)

    def get_image(self):
        if self.has_photo():
            return self._photo.pixmap().toImage()

    def has_photo(self):
        return not self._empty

    def change_image(self, img):
        self.update_image(img)
        self.fitInView()

    def img_to_pixmap(self, img):
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # bgr -> rgb
        h, w, c = img.shape  # 获取图片形状
        image = QImage(img, w, h, 3 * w, QImage.Format_RGB888)
        return QPixmap.fromImage(image)

    def update_image(self, img):
        self._empty = False
        self._photo.setPixmap(self.img_to_pixmap(img))

    def fitInView(self, scale=True):
        rect = QRectF(self._photo.pixmap().rect())
        if not rect.isNull():
            self.setSceneRect(rect)
            if self.has_photo():
                unity = self.transform().mapRect(QRectF(0, 0, 1, 1))
                self.scale(1 / unity.width(), 1 / unity.height())
                viewrect = self.viewport().rect()
                scenerect = self.transform().mapRect(rect)
                factor = min(viewrect.width() / scenerect.width(),
                             viewrect.height() / scenerect.height())
                self.scale(factor, factor)
            self._zoom = 0

    def wheelEvent(self, event):
        if self.has_photo():
            if event.angleDelta().y() > 0:
                factor = 1.25
                self._zoom += 1
            else:
                factor = 0.8
                self._zoom -= 1
            if self._zoom > 0:
                self.scale(factor, factor)
            elif self._zoom == 0:
                self.fitInView()
            else:
                self._zoom = 0
